// Device/pages/Info/components/bpgauge-component/index.js
const app = getApp();
import {
    fetchUpdatePressure
} from '@/services/device';
import {
    customNavigate
} from '@/utils/route'
import {
    showToast
} from '@/utils/util'
const userTagState = {
    '本人': 'self',
    '配偶': 'mate',
    '子女': 'sons',
    '其他': 'other'
}

const statusMappings = {
    1: '在线',
    0: '离线'
}
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        deviceInfo: {
            type: Object,
            value: {}
        }
    },
    observers: {
        deviceInfo(value) {
            const {
                blood_pressure_info,
                blood_pressures
            } = value;
            const record = blood_pressures?.[0] || {};
            const {
                measuring_time = '', user_tag = '', dbp = 0, sbp = 0, pulse = 0
            } = record;
            const sbp_max = blood_pressure_info?.[`sbp_${userTagState[user_tag]}`] || 0;
            const dbp_min = blood_pressure_info?.[`dbp_${userTagState[user_tag]}`] || 0;
            const pulse_min = blood_pressure_info?.[`pulse_min_${userTagState[user_tag]}`] || 0;
            const pulse_max = blood_pressure_info?.[`pulse_max_${userTagState[user_tag]}`] || 0;

            const data = new Map([
                ['device_status', '联网状态'],
                ['signal_strength', '信号强度']
            ]);
            let obj = {
                device_status: statusMappings[value['device_status']],
                signal_strength: value['signal_strength'] || '--'
            }
            let result = [];
            for (let [key, value] of Object.entries(obj)) {
                result.push({
                    key: data.get(key),
                    value,
                    path: '/Device/pages/Analysis/index?type=' + key
                })
            }
            this.setData({
                deviceData: result,
                record,
                sbp,
                dbp,
                sbp_max,
                dbp_min,
                pulse_min,
                pulse_max,
                pulse,
                state: user_tag ? sbp > sbp_max || dbp > dbp_min ? '异常血压' : '正常血压' : '正常血压'
            });
        }
    },
    /**
     * 组件的初始数据
     */
    data: {
        deviceData: [],
        staticPrefix: app.globalData.STATIC_PREFIX,
        sbp: 0,
        dbp: 0,
        pulse: 0,
        sbp_max: 0,
        dbp_min: 0,
        pulse_min: 0,
        pulse_max: 0,
        state: null,
        columns: ['本人', '配偶', '子女', '其他']
    },

    /**
     * 组件的方法列表
     */
    methods: {
        onTap() {
            this.setData({
                show: true
            })
        },
        onCancel() {
            this.setData({
                show: false
            })
        },
        async onConfirm(e) {
            console.log(e)
            const params = {
                user_tag: e.detail.value,
                id: this.data.record.id
            }
            const res = await fetchUpdatePressure(params);
            if (res.return_code == 'SUCCESS') {
                showToast('认领成功！', () => {
                    this.refreshPage()
                })
            }
        },
        refreshPage() {
            console.log("重新加载页面");
            const currentPage = getCurrentPages().pop(); // 获取当前页面实例
            if (currentPage) {
                const options = currentPage.options; // 获取页面参数
                wx.redirectTo({
                    url: `/${currentPage.route}?${this.getQueryString(options)}`
                });
            }
        },
        onNavigate() {
            const {
                device_type,
                product_type,
                device_imei
            } = this.data.deviceInfo;
            const params = {
                device_type,
                product_type,
                device_imei
            }
            customNavigate({
                url: `/Device/pages/History/index`,
                params
            })
        },
        onNavigateToAnalysis() {
            customNavigate({
                url: '/Device/pages/Analysis/index',
                params: {
                    device_imei: this.data.deviceInfo.device_imei
                }
            })
        },
        // 辅助函数：将参数对象转换为查询字符串
        getQueryString(options) {
            return Object.keys(options)
                .map(key => `${key}=${options[key]}`)
                .join("&");
        }
    }
})